Twilio Agent

Rishabh Jain 12 years ago
parent
commit
bd11e43dbc
2 changed files with 50 additions and 0 deletions
  1. 1 0
      Gemfile
  2. 49 0
      app/models/agents/twilio_agent.rb

+ 1 - 0
Gemfile

@@ -9,6 +9,7 @@ gem 'bootstrap-kaminari-views'
9 9
 gem "rufus-scheduler", :require => false
10 10
 gem 'json', '>= 1.7.7'
11 11
 gem 'jsonpath'
12
+gem 'twilio-ruby'
12 13
 
13 14
 gem 'delayed_job', :git => 'https://github.com/wok/delayed_job' # Until the YAML issues are fixed in master.
14 15
 gem 'delayed_job_active_record', "~> 0.3.3" # newer was giving a strange MySQL error

+ 49 - 0
app/models/agents/twilio_agent.rb

@@ -0,0 +1,49 @@
1
+require 'rubygems'
2
+require 'twilio-ruby'  
3
+
4
+module Agents
5
+	class TwilioAgent < Agent
6
+
7
+		default_schedule "every_10m"
8
+
9
+		description <<-MD
10
+			The TwilioAgent collects any events sent to it and send them via text message. 
11
+			Add more info
12
+		MD
13
+
14
+		def default_options
15
+			{
16
+				:account_sid   => "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
17
+				:auth_token    => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
18
+				:senderscell   => "xxxxxxxxxx",
19
+				:receiverscell => "xxxxxxxxxx",
20
+				:expected_receive_period_in_days => "x"
21
+			}
22
+		end
23
+
24
+		def validate_options
25
+			errors.add(:base, "account_sid,auth_token,senderscell,receiverscell are all required") unless options[:account_sid].present? && options[:auth_token].present? && options[:senderscell].present? && options[:receiverscell].present? && options[:expected_receive_period_in_days].present?
26
+		end
27
+
28
+		def receive(incoming_events)
29
+			incoming_events.each do |event|
30
+				self.memory[:queue] ||= [] # If memory[:queue] is not true, assign [] to it, a || a = b
31
+				self.memory[:queue] << event.payload # Append
32
+			end
33
+		end
34
+
35
+		def working?
36
+			last_receive_at && last_receive_at > options[:expected_receive_period_in_days].to_i.days.ago
37
+		end
38
+
39
+		def check
40
+			if self.memory[:queue] && self.memory[:queue].length > 0
41
+				@client = Twilio::REST::Client.new options[:account_sid],options[:auth_token]
42
+				self.memory[:queue].each do |text|
43
+					@client.account.sms.messages.create(:from=>options[:senderscell],:to=>options[:receiverscell],:body=>"#{text[:message]}")
44
+				end
45
+				self.memory[:queue] = []
46
+			end
47
+		end
48
+	end
49
+end